import React, { Component } from 'react';
import { Table, Form, Input, Row, Col, Select } from 'antd';
import { connect } from 'dva';
import styles from './index.less';

const FormItem = Form.Item;
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);


class EditableCell extends React.Component {
    state = {
        editing: false,
    }

    componentDidMount() {
        window.Isoption = true;
        if (this.props.editable) {
            document.addEventListener('click', this.handleClickOutside, true);
        }
    }

    componentWillUnmount() {
        window.Isoption = false;
        if (this.props.editable) {
            document.removeEventListener('click', this.handleClickOutside, true);
        }
    }

    toggleEdit = () => {
        const editing = !this.state.editing;
        this.setState({ editing }, () => {
            if (editing) {
                this.input.focus();
            }
        });
    }

    handleClickOutside = (e) => {
        const { editing } = this.state;
        if (editing && this.cell !== e.target && !this.cell.contains(e.target)) {
            this.save();
        }
    }

    save = () => {
        const { record, handleSave } = this.props;
        this.form.validateFields((error, values) => {
            if (error) {
                return;
            }
            this.toggleEdit();
            handleSave({ ...record, ...values });
        });
    }

    render() {
        const { editing } = this.state;
        const {
            editable,
            dataIndex,
            title,
            record,
            index,
            handleSave,
            ...restProps
        } = this.props;
        return (
            <td ref={node => (this.cell = node)} {...restProps}>
                {editable ? (
                    <EditableContext.Consumer>
                        {(form) => {
                            this.form = form;
                            return (
                                editing ? (
                                    <FormItem style={{ margin: 0 }}>
                                        {form.getFieldDecorator(dataIndex, {
                                            rules: [{
                                                required: true,
                                                message: `请输入${title}`,
                                            }],
                                            initialValue: record[dataIndex],
                                        })(
                                            <Input
                                                ref={node => (this.input = node)}
                                                onPressEnter={this.save}
                                            />
                                        )}
                                    </FormItem>
                                ) : (
                                        <div
                                            className="editable-cell-value-wrap"
                                            style={{ paddingRight: 24 }}
                                            onClick={this.toggleEdit}
                                        >
                                            {restProps.children}
                                        </div>
                                    )
                            );
                        }}
                    </EditableContext.Consumer>
                ) : restProps.children}
            </td>
        );
    }
}

@connect(({ global, goods }) => ({
    oemInfo: global.oemInfo,
    goods
}))
class EditableTable extends Component {
    state = {
        isShow: true,
        id: 32,
        tableList: [],
        columns: [],
        selectValue: '',
        addData: []
    }

    componentDidMount() {
        this.initData();
    }

    initData = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'goods/GetProductById',
            payload: {
                id: this.state.id
            },
            callBack: {
                success: res => {
                    let arr = [], obj = {};
                    // console.log('res.Data..', res.Data.stock)
                    res.Data.stock.length > 0 && res.Data.stock.map((item, index) => {
                        if (index == 0) {
                            if (item.k1) {
                                obj = {};
                                obj.key = index;
                                obj.title = item.k1;
                                obj.dataIndex = 'v1';
                                obj.render = (text, row, index) => {
                                    const obj = {
                                        children: text,
                                        props: {},
                                    };
                                    if (index === 0 || index === row.row_1_num) {
                                        obj.props.rowSpan = row.row_1_num;
                                    } else {
                                        obj.props.rowSpan = 0;
                                    }
                                    return obj;
                                }
                                arr.push(obj);
                            }
                            if (item.k2) {
                                obj = {};
                                obj.key = index;
                                obj.title = item.k2;
                                obj.dataIndex = 'v2';
                                obj.render = (text, row, index) => {
                                    const obj = {
                                        children: text,
                                        props: {},
                                    };

                                    if (index === 0 || index % row.row_2_num == 0) {
                                        obj.props.rowSpan = row.row_2_num;
                                    } else {
                                        obj.props.rowSpan = 0;
                                    }

                                    return obj;
                                }
                                arr.push(obj);
                            }
                            if (item.k3) {
                                obj = {};
                                obj.key = index;
                                obj.title = item.k3;
                                obj.dataIndex = 'v3';
                                arr.push(obj);
                            }
                        }
                        if (index == (res.Data.stock.length - 5)) {
                            obj = {};
                            obj.key = index;
                            obj.title = '*价格（元）';
                            obj.dataIndex = 'price';
                            obj.editable = true;
                            obj.width = '15%';
                            arr.push(obj);
                        }
                        if (index == (res.Data.stock.length - 4)) {
                            obj = {};
                            obj.key = index;
                            obj.title = '*库存';
                            obj.dataIndex = 'stock_num';
                            obj.editable = true;
                            obj.width = '13%';
                            arr.push(obj);
                        }
                        if (index == (res.Data.stock.length - 3)) {
                            obj = {};
                            obj.key = index;
                            obj.title = '规格编码';
                            obj.dataIndex = 'code';
                            obj.width = '13%';
                            arr.push(obj);
                        }
                        if (index == (res.Data.stock.length - 2)) {
                            obj = {};
                            obj.key = index;
                            obj.title = '成本价';
                            obj.dataIndex = 'cost_price';
                            obj.width = '13%';
                            arr.push(obj);
                        }
                        if (index == (res.Data.stock.length - 1)) {
                            obj = {};
                            obj.key = index;
                            obj.title = '销量';
                            obj.dataIndex = 'sale_num';
                            obj.width = '10%';
                            arr.push(obj);
                        }
                    });

                    this.setState({
                        columns: arr,
                    }, () => {
                        this.setState({
                            tableList: res.Data.stock || []
                        });
                    });
                },
                error: res => {
                    message.error(res.Msg);
                },
            },
        });
    }

    handleChange = (v) => {
        this.setState({
            selectValue: v
        });
    }


    render() {
        const components = {
            body: {
                row: EditableFormRow,
                cell: EditableCell,
            },
        };
        const columns = this.state.columns.map((col) => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    handleSave: this.handleSave,
                }),
            };
        });

        return (
            <div>
                {
                    this.state.isShow ?
                        <Table
                            components={components}
                            className={styles.tableStyle}
                            rowKey={record => record.id}
                            pagination={false}
                            bordered
                            dataSource={this.state.tableList}
                            columns={columns}
                            rowClassName="editable-row"
                        />
                        :
                        null
                }
            </div>
        );
    }
}

export default EditableTable;